package com.zerui.manager.icc.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dahuatech.hutool.http.Method;
import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.oauth.http.IClient;
import com.dahuatech.icc.oauth.model.v202010.GeneralRequest;
import com.dahuatech.icc.oauth.model.v202010.GeneralResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class AbstractBase {

    public static final String DEF_REGEX_1 = "\\{(.+?)\\}";
    public static final String DEF_REGEX_2 = "\\$\\{(.+?)\\}";

    @Resource
    private IClient iClient;

    /**
     * 通用请求信息
     *
     * @param url       请求地址
     * @param method    请求方法
     * @param bodyParam JSON请求参数
     * @param joNode    返回指定的节点
     * @return
     * @throws ClientException
     */
    public JSONObject generalRequest(final String url, final Method method, final Object bodyParam, final String joNode) throws ClientException {
        Assert.notNull(url, "请提供服务接口地址.");
        GeneralRequest generalRequest = new GeneralRequest(url, method);
        if (null != bodyParam)
            generalRequest.body(JSONObject.toJSONString(bodyParam)); // 指定参数
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        JSONObject joResult = JSONObject.parseObject(generalResponse.getResult());
        if (!"0".equals(generalResponse.getCode())) {
            throw new ClientException(generalResponse.getCode(), generalResponse.getErrMsg());
        }
        return StringUtils.isEmpty(joNode) ? joResult : joResult.getJSONObject(joNode);
    }

    /**
     * 通用请求信息 2
     *
     * @param url    请求地址
     * @param method 请求方法
     * @param bytes  form表单参数
     * @param joNode 返回指定的节点
     * @return
     * @throws ClientException
     */
    public JSONObject generalUpload(final String url, final Method method, final String fileName, final byte[] bytes, final String joNode) throws ClientException {
        Assert.notNull(url, "请提供服务接口地址.");
        GeneralRequest generalRequest = new GeneralRequest(url, method);
        generalRequest.getHttpRequest().contentType("multipart/form-data");
        generalRequest.getHttpRequest().form("file", bytes, fileName);
        GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
        JSONObject joResult = JSONObject.parseObject(generalResponse.getResult());
        if (!"0".equals(generalResponse.getCode())) {
            throw new ClientException(generalResponse.getCode(), generalResponse.getErrMsg());
        }
        return StringUtils.isEmpty(joNode) ? joResult : joResult.getJSONObject(joNode);
    }

    /**
     * 将数据转换成指定类型
     *
     * @param json  JSON数据对象
     * @param clazz 要转换的数据类型
     * @param <T>   指定的类型
     * @return
     */
    public <T> List<T> convert2TypeData(JSON json, Class<T> clazz) {
        if (json instanceof JSONArray) { // 如果是数组
            JSONArray jrr = (JSONArray) json;
            List<T> ts = JSONArray.parseArray(jrr.toJSONString(), clazz);
            return ts;
        } else if (json instanceof JSONObject) { // 如果是对象
            JSONObject jo = (JSONObject) json;
            T t = JSONObject.parseObject(jo.toJSONString(), clazz);
            return Collections.singletonList(t);
        }
        return Collections.emptyList();
    }

    /**
     * 替换 {id} 占位符数据
     *
     * @param url       请求地址
     * @param paramData 参数数据
     * @return
     */
    protected String renderUrl(String url, Map<String, String> paramData) {
        if (url == null || url.trim().isEmpty()) {
            return "";
        }
        if (paramData == null || paramData.size() == 0) {
            return url;
        }
        try {
            StringBuffer appendReplaceSb = new StringBuffer();
            Pattern pattern = Pattern.compile(DEF_REGEX_1);
            Matcher matcher = pattern.matcher(url);
            while (matcher.find()) {
                // String currentStr = matcher.group(0);//整个正则匹配的字符串
                String key = matcher.group(1);//当前第一个子分组正则匹配的字符串
                String value = paramData.get(key);
                 /*Matcher. appendReplacement：将当前匹配的子字符串替换为指定的字符串，并且将替换后的字符串
                及其之前到上次匹配的子字符串之后的字符串添加到一个StringBuffer对象中。*/
                matcher.appendReplacement(appendReplaceSb, value);//
            }
            /*   Matcher. appendTail：将最后一次匹配之后的字符串添加到一个StringBuffer对象中。*/
            matcher.appendTail(appendReplaceSb);
            return appendReplaceSb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }


}
